;
(function($){
    $.extend($.jgrid, {
        customSaveBtnEvent: function(config){
            if (config.commonServiceName == undefined || config.commonServiceName.length < 1) {
                config.commonServiceName = "CommonService";
            }
            
            // 重置按钮
            if (config.resetBtnId) {
                $('#' + config.resetBtnId).bind('click', function(){
                    $(config.editFormSelector).trigger("reset");
                });
            }
            //1.取到实体名称与ID名称
            config.objectProp = $.StringUtils.getEntityName(config.objectName);
            config.objectId = $.StringUtils.getEntityId(config.objectProp);
            
            //2. 获取从url传递的参数
            var objectIdVal = getIdVal();
            
            if (objectIdVal.length > 0) {
                //3. 查询主表数据
                if (config.autoLoad === true) {
                    var initProps = config.initProps ? config.initProps.split(",") : [];
                    var field = {
                        "fieldName": config.objectId,
                        fieldValueString: objectIdVal
                    };
                    var queryInfo = {
                        queryObjectName: config.objectName,
                        listType: "list",
                        fields: [field]
                    };
                    eval($.StringUtils.firstUpperCase(config.commonServiceName))["findByQueryInit"](queryInfo, initProps, $.DwrUtils.proDwrOption({
                        async: false,
                        callback: function(result){
                            FormUtils.convertSimpleObject2FormBySelector(result[0], config.editFormSelector);
                            //执行数据处理后方法
                            if ($.isFunction(config.afterProcessing)) {
                                config.afterProcessing.call(config, result[0]);
                            }
                            //将数据保存在表单
                            $.FormUtils.setFormData(config.editFormSelector, result[0]);
                        }
                    }));
                }
            }
            if (config.editFormSelector) {
                //触发keyup 事件立即启用保存按钮
                
                $(config.editFormSelector).bind("click keyup focus change", function(e){
					var $target = $($.EventUtils.getTargetByEvent(e));
					
					//禁用 和 只读控件 不能激活 保存按钮
					if((($target.is("input") || $target.is("textarea")) && ($target.attr("readonly")==true || $target.attr("readonly")=="readonly")) 
						|| $target.attr("disabled")==true || $target.attr("disabled")=="disabled"){
						return;
					}
					//下拉框,radio,checkbox
					if(($target.is("select") || $target.is("input:checkbox") || $target.is("input:radio")) && e.type == "change"){
						enabledSaveBtn(true);
						return;
					}
					//联想控件 附属的按钮
					if($target.is("button[id$='_image_associate']") && $target.hasClass("associateImage") && e.type == "click"){
						enabledSaveBtn(true);
						return;
					}
					//文本域
					if($target.is("textarea") && e.type == "keyup"){
						enabledSaveBtn(true);
						return;
					}
					//其它输入框					
					if(($target.is("input:text") || $target.is("input:password")) && e.type == "keyup"){
						enabledSaveBtn(true);
						return;
					}
                });
				//日期控件
				$(config.editFormSelector).find("input:text.Wdate").bind("focus click",function(e){
					enabledSaveBtn(true);
					return;
				});
                
                //打开校验规则的提示
                $.jqValidator.setIsShowValidateMsg(config.editFormSelector, true);
            }
            if (config.saveBtnId) {
                //初始化控件验证规则
                $.jqValidator.initValidateRules(config.editFormSelector);
                //初始化控件格式化规则
                $.jqFormatter.initFormatRules(config.editFormSelector);
                $("#" + config.saveBtnId).bind('click', function(e){
                
                    //验证表单
                    if (!$.jqValidator.validateForm(config.editFormSelector)) {
                        return;
                    }
					//验证子表
					if(config.subGridMaps && !$.jgrid.validateSubGridMaps(config.subGridMaps)){return ;}
					
                    var formData = $.FormUtils.getFormData(config.editFormSelector);
                    //组装表单数据
                    FormUtils.convertSimpleForm2ObjectBySelector(config.editFormSelector, formData);
                    //alert($.objToJSONString(formData));
                    
                    //判断 新增 还是 修改数据
                    objectIdVal = getIdVal();
                    if (objectIdVal.length > 0) {
                        formData.rowStatus = Gfa.GlobalConstant.ROWSTATUS_MODIFIED;
                    }
                    else {
                        formData.rowStatus = Gfa.GlobalConstant.ROWSTATUS_ADDED;
                    }
                    
                    //收集子表数据
                    $(config.subGridMaps).each(function(ind, elm){
                        var subGrid = $('#' + elm.gridId), subGridConfig = subGrid[0].p;
						
                        var subDatas = subGrid.jqGrid('getPrepareRowDatas');
                        if (subDatas.length > 0) {
                            for (var sd = 0; sd < subDatas.length; sd++) {
                                var subData = subDatas[sd];
                                subData[config.objectId] = objectIdVal;
                                subData[config.objectProp] = formData;
                            }
                        }
                        formData[elm.propName] = subDatas;
                    })
                    //保存前方法
                    if (config.beforeSave) {
                        if (!(config.beforeSave.call(this, formData))) {
                            return false;
                        }
                    }
                    //屏蔽按钮
                    enabledSaveBtn(false);
                    //保存option 定义
                    var dwrOption = {
                        callback: function(result){
                            //保存后返回的对象再填充到表单
                            FormUtils.convertSimpleObject2FormBySelector(result, config.editFormSelector);
                            //将数据保存在表单
                            $.FormUtils.setFormData(config.editFormSelector, result);
                            
                            //同时刷新子表
                            $.jgrid.reloadSubGrids(config.subGridMaps);
                            //回调自定义方法
                            if (config.callback && $.isFunction(config.callback)) {
                                config.callback(result);
                            }
                        }
                    }
                    if (config.saveError && $.isFunction(config.saveError)) {
                        $.extend(dwrOption, {
                            errorHandler: function(message){
                                config.saveError.call(config, message);
                            },
                            exceptionHandler: function(message){
                                config.saveError.call(config, message);
                            }
                        });
                    }
                    //alert($.objToJSONString(formData));
                    var dwrFunc = eval(config.serviceName)[config.serviceMethodName];
                    //11.支持多参数的servcie
                    var dwrArgs = [];
					var formDwrServiceArguments = $.FormUtils.getDwrServiceArguments(config.editFormSelector);
                    if ($.isArray(formDwrServiceArguments)) {
                        dwrArgs = formDwrServiceArguments;
                        dwrArgs.push($.DwrUtils.proDwrOption(dwrOption));
                    } else {
                        dwrArgs.push(formData);
                        dwrArgs.push($.DwrUtils.proDwrOption(dwrOption));
                    }
                    //12.执行service 方法
                    dwrFunc.apply(this, dwrArgs);
                });
            }
            function getIdVal(){
                var retIdVal = "";
                //1. 获取从url传递的参数
                retIdVal = $.getQueryString(config.objectId)?$.getQueryString(config.objectId):$.getQueryString("id");
                //alert(objectIdVal);
                //2. Url获取不到，可以从隐藏域获取
                if (retIdVal.length < 1 && config.objectId && config.objectId.length > 0) {
                    retIdVal = $("input[name='" + config.objectId + "']", config.editFormSelector).val()
                }
                return retIdVal;
            }
            function enabledSaveBtn(enabled){
                var saveBtnState = $("#" + config.saveBtnId).attr("disabled");
                //启用保存按钮
                if (!$.StringUtils.isEmpty(saveBtnState) && enabled === true &&
                (saveBtnState === true || saveBtnState === "disabled" || saveBtnState == "disabled")) {
                    $("#" + config.saveBtnId).attr("disabled", false);
                }
                //禁用保存按钮
                else if (enabled === false) {
                    $("#" + config.saveBtnId).attr("disabled", true);
                }
            }
        },
		/**
		 * 验证子表
		 * @param {Object} grids
		 */
		validateSubGridMaps : function(grids){
			for (var i = 0; i < grids.length; i++) {
				var subGrid = $('#' + grids[i].gridId), subGridConfig = subGrid[0].p;
				//验证子表
				if (subGridConfig.enabledValidateForm === true && !$.jqValidator.validateForm(subGridConfig.editFormSelector)) {
					return false;
				}
				var subs = subGridConfig.subGridMaps;
				if(subs && subs.length > 0){
					if(!$.jgrid.validateSubGridMaps(subs)) return false;
				}
			}
			return true;
		}
    });
    
    /**
     * 自定义保存的service method要提交多个参数，需要对$.FormUtils 进行扩展
     * setDwrServiceArguments,getDwrServiceArguments仅限于自定义保存
     */
    $.extend($.FormUtils, {
        dwrServiceArgumentsKey: "dwrServiceArguments",
        /**
         *
         * @param {Object} formSelect
         * @param {Object} _arguments
         */
        setDwrServiceArguments: function(formSelect, _serviceArgument){
            var form, $forms = $(formSelect);
            if ($forms.length > 0) {
                form = $forms[0];
                $.data(form, $.FormUtils.dwrServiceArgumentsKey, _serviceArgument);
            }
        },
        /**
         *
         * @param {Object} formSelect
         */
        getDwrServiceArguments: function(formSelect){
            var form, $forms = $(formSelect);
            if ($forms.length > 0) {
                form = $forms[0];
            }
            return $.data(form, $.FormUtils.dwrServiceArgumentsKey);
        }
    });
})(jQuery);
